package servlet;

import Dao.StudentDao;
import Dao.UserDao;
import Impl.StudentDaoImpl;
import com.google.gson.Gson;
import model.Result;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/DeleteUserServlet")
public class DeleteUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //客户端传来学号
        String stuNo=request.getParameter("stuNo");
        UserDao userDao=new UserDao();
        String userName=userDao.getIdByStuNo(stuNo);//通过学号获取username
        System.out.println("username"+userName);

        PrintWriter writer=response.getWriter();
        Gson gson=new Gson();
        //要将客户端传过来的用户信息与session中的用户信息进行配对，以免删除的是当前用户
        User u=(User)request.getSession().getAttribute("user");
        if(u.getUserName().equals(userName)){
            //无法删除本用户信息
            writer.write(gson.toJson(new Result("false")));
        }else {
            StudentDaoImpl studentDao=new StudentDao();
            int result=0;
            System.out.println("BBB");
            if(userDao.deleteUser(userName)>0)
                result=studentDao.deleteStudent(stuNo);
            if(result>0)
                writer.write(gson.toJson(new Result("ok")));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
